const express = require('express');
const axios = require('axios');
const cors = require('cors');
const iconv = require('iconv-lite');
const path = require('path');

const app = express();
const PORT = 3000;

// 启用CORS
app.use(cors());
app.use(express.static(path.join(__dirname, '../public'))); // 静态文件服务

// 检查当前是否为交易时间 (9:00 - 16:00)
function isTradingHours() {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const currentTime = hour * 60 + minute; // 转换为分钟

    // 交易时间：9:00-16:00 (540 - 960分钟)
    // 周末不交易
    const dayOfWeek = now.getDay(); // 0是周日，6是周六

    return dayOfWeek >= 1 && dayOfWeek <= 5 && currentTime >= 540 && currentTime < 960;
}

// A股股票代码生成函数
function generateAllStockCodes() {
    const stockCodes = [];

    // 深圳主板：000xxx
    for (let i = 1; i <= 999; i++) {
        const code = String(i).padStart(6, '0');
        if (code.startsWith('000')) {
            stockCodes.push({ code, market: 'sz', type: '主板' });
        }
    }

    // 深圳中小板：002xxx
    for (let i = 1; i <= 999; i++) {
        const code = '002' + String(i).padStart(3, '0');
        stockCodes.push({ code, market: 'sz', type: '中小板' });
    }

    // 深圳创业板：300xxx
    for (let i = 1; i <= 999; i++) {
        const code = '300' + String(i).padStart(3, '0');
        stockCodes.push({ code, market: 'sz', type: '创业板' });
    }

    // 上海主板：600xxx, 601xxx, 603xxx, 605xxx
    for (let i = 0; i <= 999; i++) {
        const num = String(i).padStart(3, '0');
        stockCodes.push({ code: '600' + num, market: 'sh', type: '主板' });
        stockCodes.push({ code: '601' + num, market: 'sh', type: '主板' });
        stockCodes.push({ code: '603' + num, market: 'sh', type: '主板' });
        if (i <= 199) { // 605xxx 范围较小
            stockCodes.push({ code: '605' + num, market: 'sh', type: '主板' });
        }
    }

    // 科创板：688xxx
    for (let i = 1; i <= 999; i++) {
        const code = '688' + String(i).padStart(3, '0');
        stockCodes.push({ code, market: 'sh', type: '科创板' });
    }

    return stockCodes;
}

// 动态股票名称映射缓存
const stockNameCache = new Map();
const stockCodeDatabase = generateAllStockCodes();

// 常见股票名称映射（作为快速查找）
const commonStockNameMap = {
    '平安银行': '000001',
    '万科A': '000002',
    '五粮液': '000858',
    '贵州茅台': '600519',
    '招商银行': '600036',
    '浦发银行': '600000',
    '中国平安': '601318',
    '比亚迪': '002594',
    '宁德时代': '300750',
    '格力电器': '000651',
    '美的集团': '000333',
    '海康威视': '002415',
    '迈瑞医疗': '300760',
    '智飞生物': '300122',
    '长春高新': '000661',
    '恒瑞医药': '600276',
    '药明康德': '603259',
    '中国中免': '601888',
    '伊利股份': '600887',
    '海天味业': '603288',
    '中国石油': '601857',
    '工商银行': '601398',
    '建设银行': '601939',
    '农业银行': '601288',
    '中国银行': '601988',
    '中国神华': '601088',
    '中国建筑': '601668',
    '浪潮信息': '000977',
    '巨人网络': '002558',
    '京东方A': '000725',
    '中兴通讯': '000063',
    '立讯精密': '002475',
    '东方财富': '300059',
    '同花顺': '300033',
    '中信证券': '600030',
    '华泰证券': '601688',
    '国泰君安': '601211',
    '紫金矿业': '601899',
    '宝钢股份': '600019',
    '中国铝业': '601600',
    '江西铜业': '600362'
};

// 向后兼容的stockNameMap
const stockNameMap = new Proxy(commonStockNameMap, {
    get(target, prop) {
        // 首先检查常见股票映射
        if (target[prop]) {
            return target[prop];
        }

        // 检查缓存
        if (stockNameCache.has(prop)) {
            return stockNameCache.get(prop);
        }

        return undefined;
    },

    set(target, prop, value) {
        // 设置到常见股票映射
        target[prop] = value;
        // 同时设置到缓存
        stockNameCache.set(prop, value);
        return true;
    }
});

// 智能股票搜索函数
async function searchStockByName(stockName, maxResults = 10) {
    console.log('开始智能股票搜索:', stockName);
    const results = [];
    const searchTerms = stockName.trim().toLowerCase();

    // 限制搜索的股票代码范围，避免过多API调用
    // 优先搜索热门股票代码段
    const searchPriorityCodes = [
        // 深圳主板热门
        '000001', '000002', '000004', '000005', '000006', '000007', '000008', '000009', '000010', '000011',
        '000012', '000014', '000016', '000017', '000019', '000020', '000021', '000022', '000025', '000027',
        '000028', '000029', '000030', '000031', '000032', '000034', '000035', '000036', '000037', '000038',
        '000039', '000040', '000042', '000043', '000045', '000046', '000048', '000049', '000050', '000055',
        '000056', '000058', '000059', '000060', '000061', '000062', '000063', '000065', '000066', '000068',
        '000069', '000070', '000078', '000088', '000089', '000090', '000096', '000099', '000100', '000157',
        '000158', '000159', '000301', '000333', '000338', '000400', '000401', '000402', '000403', '000404',
        '000488', '000490', '000501', '000502', '000503', '000505', '000506', '000507', '000510', '000511',
        '000513', '000516', '000517', '000518', '000520', '000521', '000523', '000525', '000526', '000527',
        '000528', '000529', '000530', '000531', '000532', '000533', '000534', '000535', '000536', '000537',
        '000538', '000539', '000540', '000541', '000542', '000543', '000544', '000545', '000546', '000547',
        '000548', '000550', '000551', '000552', '000553', '000554', '000555', '000556', '000557', '000558',
        '000559', '000560', '000561', '000562', '000563', '000564', '000565', '000566', '000567', '000568',
        '000569', '000570', '000571', '000572', '000573', '000580', '000581', '000582', '000584', '000585',
        '000586', '000587', '000588', '000589', '000590', '000591', '000592', '000593', '000595', '000596',
        '000597', '000598', '000599', '000600', '000601', '000603', '000605', '000606', '000607', '000608',
        '000609', '000610', '000611', '000612', '000613', '000615', '000616', '000617', '000618', '000619',
        '000620', '000622', '000623', '000625', '000626', '000627', '000628', '000629', '000630', '000631',
        '000632', '000633', '000635', '000636', '000637', '000638', '000639', '000650', '000651', '000652',
        '000655', '000656', '000657', '000658', '000659', '000660', '000661', '000662', '000663', '000665',
        '000666', '000667', '000668', '000669', '000670', '000671', '000672', '000673', '000675', '000676',
        '000677', '000678', '000679', '000680', '000681', '000682', '000683', '000685', '000686', '000687',
        '000688', '000689', '000690', '000691', '000692', '000693', '000695', '000696', '000697', '000698',
        '000699', '000700', '000701', '000702', '000703', '000705', '000706', '000707', '000708', '000709',
        '000710', '000711', '000712', '000713', '000715', '000716', '000717', '000718', '000719', '000720',
        '000721', '000722', '000723', '000725', '000726', '000727', '000728', '000729', '000730', '000731',
        '000732', '000733', '000735', '000736', '000737', '000738', '000739', '000750', '000751', '000752',
        '000753', '000755', '000756', '000757', '000758', '000759', '000760', '000761', '000762', '000763',
        '000765', '000766', '000767', '000768', '000769', '000770', '000771', '000772', '000773', '000775',
        '000776', '000777', '000778', '000779', '000780', '000781', '000782', '000783', '000785', '000786',
        '000787', '000788', '000789', '000790', '000791', '000792', '000793', '000795', '000796', '000797',
        '000798', '000799', '000800', '000801', '000802', '000803', '000805', '000806', '000807', '000809',
        '000810', '000811', '000812', '000813', '000815', '000816', '000817', '000818', '000819', '000820',
        '000821', '000822', '000823', '000826', '000827', '000828', '000829', '000830', '000831', '000832',
        '000833', '000834', '000835', '000836', '000837', '000838', '000839', '000848', '000850', '000851',
        '000852', '000855', '000856', '000858', '000859', '000860', '000861', '000862', '000863', '000865',
        '000866', '000867', '000868', '000869', '000870', '000873', '000875', '000876', '000877', '000878',
        '000880', '000881', '000882', '000883', '000885', '000886', '000887', '000888', '000889', '000890',
        '000891', '000892', '000893', '000895', '000896', '000897', '000898', '000899', '000900', '000901',
        '000902', '000903', '000905', '000906', '000907', '000908', '000909', '000910', '000911', '000912',
        '000913', '000915', '000916', '000917', '000918', '000919', '000920', '000921', '000922', '000923',
        '000925', '000926', '000927', '000928', '000929', '000930', '000931', '000932', '000933', '000935',
        '000936', '000937', '000938', '000948', '000949', '000950', '000951', '000952', '000953', '000957',
        '000958', '000959', '000960', '000961', '000962', '000963', '000965', '000966', '000967', '000968',
        '000969', '000970', '000971', '000972', '000973', '000977', '000978', '000979', '000980', '000981',
        '000982', '000983', '000985', '000987', '000988', '000989', '000990', '000991', '000992', '000993',
        '000995', '000996', '000997', '000998', '000999',

        // 深圳中小板热门
        '002001', '002002', '002003', '002004', '002005', '002006', '002007', '002008', '002009', '002010',
        '002011', '002012', '002013', '002014', '002015', '002016', '002017', '002018', '002019', '002020',
        '002021', '002022', '002023', '002024', '002025', '002026', '002027', '002028', '002029', '002030',
        '002031', '002032', '002033', '002034', '002035', '002036', '002037', '002038', '002039', '002040',
        '002041', '002042', '002043', '002044', '002045', '002046', '002047', '002048', '002049', '002050',
        '002051', '002052', '002053', '002054', '002055', '002056', '002057', '002058', '002059', '002060',
        '002061', '002062', '002063', '002064', '002065', '002066', '002067', '002068', '002069', '002070',
        '002071', '002072', '002073', '002074', '002075', '002076', '002077', '002078', '002079', '002080',
        '002081', '002082', '002083', '002084', '002085', '002086', '002087', '002088', '002089', '002090',
        '002091', '002092', '002093', '002094', '002095', '002096', '002097', '002098', '002099', '002100',
        '002101', '002102', '002103', '002104', '002105', '002106', '002107', '002108', '002109', '002110',
        '002111', '002112', '002113', '002114', '002115', '002116', '002117', '002118', '002119', '002120',
        '002121', '002122', '002123', '002124', '002125', '002126', '002127', '002128', '002129', '002130',
        '002131', '002132', '002133', '002134', '002135', '002136', '002137', '002138', '002139', '002140',
        '002141', '002142', '002143', '002144', '002145', '002146', '002147', '002148', '002149', '002150',
        '002151', '002152', '002153', '002154', '002155', '002156', '002157', '002158', '002159', '002160',
        '002161', '002162', '002163', '002164', '002165', '002166', '002167', '002168', '002169', '002170',
        '002171', '002172', '002173', '002174', '002175', '002176', '002177', '002178', '002179', '002180',
        '002181', '002182', '002183', '002184', '002185', '002186', '002187', '002188', '002189', '002190',
        '002191', '002192', '002193', '002194', '002195', '002196', '002197', '002198', '002199', '002200',
        '002201', '002202', '002203', '002204', '002205', '002206', '002207', '002208', '002209', '002210',
        '002211', '002212', '002213', '002214', '002215', '002216', '002217', '002218', '002219', '002220',
        '002221', '002222', '002223', '002224', '002225', '002226', '002227', '002228', '002229', '002230',
        '002231', '002232', '002233', '002234', '002235', '002236', '002237', '002238', '002239', '002240',
        '002241', '002242', '002243', '002244', '002245', '002246', '002247', '002248', '002249', '002250',
        '002251', '002252', '002253', '002254', '002255', '002256', '002257', '002258', '002259', '002260',
        '002261', '002262', '002263', '002264', '002265', '002266', '002267', '002268', '002269', '002270',
        '002271', '002272', '002273', '002274', '002275', '002276', '002277', '002278', '002279', '002280',
        '002281', '002282', '002283', '002284', '002285', '002286', '002287', '002288', '002289', '002290',
        '002291', '002292', '002293', '002294', '002295', '002296', '002297', '002298', '002299', '002300',
        '002301', '002302', '002303', '002304', '002305', '002306', '002307', '002308', '002309', '002310',
        '002311', '002312', '002313', '002314', '002315', '002316', '002317', '002318', '002319', '002320',
        '002321', '002322', '002323', '002324', '002325', '002326', '002327', '002328', '002329', '002330',
        '002331', '002332', '002333', '002334', '002335', '002336', '002337', '002338', '002339', '002340',
        '002341', '002342', '002343', '002344', '002345', '002346', '002347', '002348', '002349', '002350',
        '002351', '002352', '002353', '002354', '002355', '002356', '002357', '002358', '002359', '002360',
        '002361', '002362', '002363', '002364', '002365', '002366', '002367', '002368', '002369', '002370',
        '002371', '002372', '002373', '002374', '002375', '002376', '002377', '002378', '002379', '002380',
        '002381', '002382', '002383', '002384', '002385', '002386', '002387', '002388', '002389', '002390',
        '002391', '002392', '002393', '002394', '002395', '002396', '002397', '002398', '002399', '002400',
        '002401', '002402', '002403', '002404', '002405', '002406', '002407', '002408', '002409', '002410',
        '002411', '002412', '002413', '002414', '002415', '002416', '002417', '002418', '002419', '002420',
        '002421', '002422', '002423', '002424', '002425', '002426', '002427', '002428', '002429', '002430',
        '002431', '002432', '002433', '002434', '002435', '002436', '002437', '002438', '002439', '002440',
        '002441', '002442', '002443', '002444', '002445', '002446', '002447', '002448', '002449', '002450',
        '002451', '002452', '002453', '002454', '002455', '002456', '002457', '002458', '002459', '002460',
        '002461', '002462', '002463', '002464', '002465', '002466', '002467', '002468', '002469', '002470',
        '002471', '002472', '002473', '002474', '002475', '002476', '002477', '002478', '002479', '002480',
        '002481', '002482', '002483', '002484', '002485', '002486', '002487', '002488', '002489', '002490',
        '002491', '002492', '002493', '002494', '002495', '002496', '002497', '002498', '002499', '002500',
        '002501', '002502', '002503', '002504', '002505', '002506', '002507', '002508', '002509', '002510',
        '002511', '002512', '002513', '002514', '002515', '002516', '002517', '002518', '002519', '002520',
        '002521', '002522', '002523', '002524', '002525', '002526', '002527', '002528', '002529', '002530',
        '002531', '002532', '002533', '002534', '002535', '002536', '002537', '002538', '002539', '002540',
        '002541', '002542', '002543', '002544', '002545', '002546', '002547', '002548', '002549', '002550',
        '002551', '002552', '002553', '002554', '002555', '002556', '002557', '002558', '002559', '002560',
        '002561', '002562', '002563', '002564', '002565', '002566', '002567', '002568', '002569', '002570',
        '002571', '002572', '002573', '002574', '002575', '002576', '002577', '002578', '002579', '002580',
        '002581', '002582', '002583', '002584', '002585', '002586', '002587', '002588', '002589', '002590',
        '002591', '002592', '002593', '002594', '002595', '002596', '002597', '002598', '002599', '002600',
        '002601', '002602', '002603', '002604', '002605', '002606', '002607', '002608', '002609', '002610',
        '002611', '002612', '002613', '002614', '002615', '002616', '002617', '002618', '002619', '002620',
        '002621', '002622', '002623', '002624', '002625', '002626', '002627', '002628', '002629', '002630',
        '002631', '002632', '002633', '002634', '002635', '002636', '002637', '002638', '002639', '002640',
        '002641', '002642', '002643', '002644', '002645', '002646', '002647', '002648', '002649', '002650',
        '002651', '002652', '002653', '002654', '002655', '002656', '002657', '002658', '002659', '002660',
        '002661', '002662', '002663', '002664', '002665', '002666', '002667', '002668', '002669', '002670',
        '002671', '002672', '002673', '002674', '002675', '002676', '002677', '002678', '002679', '002680',
        '002681', '002682', '002683', '002684', '002685', '002686', '002687', '002688', '002689', '002690',
        '002691', '002692', '002693', '002694', '002695', '002696', '002697', '002698', '002699', '002700',
        '002701', '002702', '002703', '002704', '002705', '002706', '002707', '002708', '002709', '002710',
        '002711', '002712', '002713', '002714', '002715', '002716', '002717', '002718', '002719', '002720',
        '002721', '002722', '002723', '002724', '002725', '002726', '002727', '002728', '002729', '002730',
        '002731', '002732', '002733', '002734', '002735', '002736', '002737', '002738', '002739', '002740',
        '002741', '002742', '002743', '002744', '002745', '002746', '002747', '002748', '002749', '002750',
        '002751', '002752', '002753', '002754', '002755', '002756', '002757', '002758', '002759', '002760',
        '002761', '002762', '002763', '002764', '002765', '002766', '002767', '002768', '002769', '002770',
        '002771', '002772', '002773', '002774', '002775', '002776', '002777', '002778', '002779', '002780',
        '002781', '002782', '002783', '002784', '002785', '002786', '002787', '002788', '002789', '002790',
        '002791', '002792', '002793', '002794', '002795', '002796', '002797', '002798', '002799', '002800',
        '002801', '002802', '002803', '002804', '002805', '002806', '002807', '002808', '002809', '002810',
        '002811', '002812', '002813', '002814', '002815', '002816', '002817', '002818', '002819', '002820',
        '002821', '002822', '002823', '002824', '002825', '002826', '002827', '002828', '002829', '002830',
        '002831', '002832', '002833', '002834', '002835', '002836', '002837', '002838', '002839', '002840',
        '002841', '002842', '002843', '002844', '002845', '002846', '002847', '002848', '002849', '002850',
        '002851', '002852', '002853', '002854', '002855', '002856', '002857', '002858', '002859', '002860',
        '002861', '002862', '002863', '002864', '002865', '002866', '002867', '002868', '002869', '002870',
        '002871', '002872', '002873', '002874', '002875', '002876', '002877', '002878', '002879', '002880',
        '002881', '002882', '002883', '002884', '002885', '002886', '002887', '002888', '002889', '002890',
        '002891', '002892', '002893', '002894', '002895', '002896', '002897', '002898', '002899', '002900',
        '002901', '002902', '002903', '002904', '002905', '002906', '002907', '002908', '002909', '002910',
        '002911', '002912', '002913', '002914', '002915', '002916', '002917', '002918', '002919', '002920',
        '002921', '002922', '002923', '002924', '002925', '002926', '002927', '002928', '002929', '002930',
        '002931', '002932', '002933', '002934', '002935', '002936', '002937', '002938', '002939', '002940',
        '002941', '002942', '002943', '002944', '002945', '002946', '002947', '002948', '002949', '002950',
        '002951', '002952', '002953', '002954', '002955', '002956', '002957', '002958', '002959', '002960',
        '002961', '002962', '002963', '002964', '002965', '002966', '002967', '002968', '002969', '002970',
        '002971', '002972', '002973', '002974', '002975', '002976', '002977', '002978', '002979', '002980',
        '002981', '002982', '002983', '002984', '002985', '002986', '002987', '002988', '002989', '002990',
        '002991', '002992', '002993', '002994', '002995', '002996', '002997', '002998', '002999',

        // 上海主板热门
        '600000', '600001', '600002', '600003', '600004', '600005', '600006', '600007', '600008', '600009',
        '600010', '600011', '600012', '600015', '600016', '600017', '600018', '600019', '600020', '600021',
        '600022', '600023', '600025', '600026', '600027', '600028', '600029', '600030', '600031', '600032',
        '600033', '600035', '600036', '600037', '600038', '600039', '600048', '600050', '600051', '600052',
        '600053', '600054', '600055', '600056', '600057', '600058', '600059', '600060', '600061', '600062',
        '600063', '600064', '600066', '600067', '600068', '600069', '600070', '600071', '600072', '600073',
        '600074', '600075', '600076', '600077', '600078', '600079', '600080', '600081', '600082', '600083',
        '600084', '600085', '600086', '600087', '600088', '600089', '600090', '600091', '600092', '600093',
        '600094', '600095', '600096', '600097', '600098', '600099', '600100', '600101', '600104', '600105',
        '600106', '600107', '600108', '600109', '600110', '600111', '600112', '600113', '600114', '600115',
        '600116', '600117', '600118', '600119', '600120', '600121', '600122', '600123', '600125', '600126',
        '600127', '600128', '600129', '600130', '600131', '600132', '600133', '600135', '600136', '600137',
        '600138', '600139', '600141', '600143', '600145', '600146', '600147', '600148', '600149', '600150',
        '600151', '600152', '600153', '600154', '600155', '600156', '600157', '600158', '600159', '600160',
        '600161', '600162', '600163', '600165', '600166', '600167', '600168', '600169', '600170', '600171',
        '600172', '600173', '600174', '600175', '600176', '600177', '600178', '600179', '600180', '600181',
        '600182', '600183', '600184', '600185', '600186', '600187', '600188', '600189', '600190', '600191',
        '600192', '600193', '600195', '600196', '600197', '600198', '600199', '600200', '600201', '600202',
        '600203', '600204', '600205', '600206', '600207', '600208', '600209', '600210', '600211', '600212',
        '600213', '600214', '600215', '600216', '600217', '600218', '600219', '600220', '600221', '600222',
        '600223', '600224', '600225', '600226', '600227', '600228', '600229', '600230', '600231', '600232',
        '600233', '600234', '600235', '600236', '600237', '600238', '600239', '600240', '600241', '600242',
        '600243', '600244', '600245', '600246', '600247', '600248', '600249', '600250', '600251', '600252',
        '600253', '600254', '600255', '600256', '600257', '600258', '600259', '600260', '600261', '600262',
        '600263', '600264', '600265', '600266', '600267', '600268', '600269', '600270', '600271', '600272',
        '600273', '600274', '600275', '600276', '600277', '600278', '600279', '600280', '600281', '600282',
        '600283', '600284', '600285', '600286', '600287', '600288', '600289', '600290', '600291', '600292',
        '600293', '600294', '600295', '600296', '600297', '600298', '600299', '600300', '600301', '600302',
        '600303', '600304', '600305', '600306', '600307', '600308', '600309', '600310', '600311', '600312',
        '600313', '600315', '600316', '600317', '600318', '600319', '600320', '600321', '600322', '600323',
        '600325', '600326', '600327', '600328', '600329', '600330', '600331', '600332', '600333', '600335',
        '600336', '600337', '600338', '600339', '600340', '600341', '600342', '600343', '600345', '600346',
        '600347', '600348', '600349', '600350', '600351', '600352', '600353', '600354', '600355', '600356',
        '600357', '600358', '600359', '600360', '600361', '600362', '600363', '600365', '600366', '600367',
        '600368', '600369', '600370', '600371', '600372', '600373', '600375', '600376', '600377', '600378',
        '600379', '600380', '600381', '600382', '600383', '600384', '600385', '600386', '600387', '600388',
        '600389', '600390', '600391', '600392', '600393', '600395', '600396', '600397', '600398', '600399',
        '600400', '600401', '600402', '600403', '600404', '600405', '600406', '600407', '600408', '600409',
        '600410', '600411', '600412', '600413', '600415', '600416', '600417', '600418', '600419', '600420',
        '600421', '600422', '600423', '600425', '600426', '600428', '600429', '600433', '600435', '600436',
        '600438', '600446', '600448', '600449', '600460', '600461', '600462', '600463', '600466', '600467',
        '600468', '600469', '600470', '600471', '600477', '600478', '600480', '600481', '600482', '600483',
        '600487', '600488', '600489', '600490', '600491', '600492', '600493', '600495', '600496', '600497',
        '600498', '600499', '600500', '600501', '600502', '600503', '600506', '600507', '600508', '600509',
        '600510', '600511', '600512', '600513', '600515', '600516', '600517', '600518', '600519', '600520',
        '600521', '600522', '600523', '600525', '600526', '600527', '600528', '600529', '600530', '600531',
        '600532', '600533', '600535', '600536', '600537', '600538', '600539', '600540', '600543', '600545',
        '600546', '600547', '600548', '600549', '550550', '600551', '600552', '600553', '600555', '600556',
        '600557', '600558', '600559', '600560', '600561', '600562', '600563', '600564', '600565', '600566',
        '600567', '600568', '600569', '600570', '600571', '600572', '600580', '600581', '600582', '600583',
        '600584', '600585', '600586', '600587', '600588', '600589', '600590', '600591', '600592', '600593',
        '600594', '600595', '600596', '600597', '600598', '600600', '600601', '600602', '600603', '600604',
        '600605', '600606', '600607', '600608', '600609', '600610', '600611', '600612', '600613', '600614',
        '600615', '600616', '600617', '600618', '600619', '600620', '600621', '600623', '600624', '600625',
        '600626', '600627', '600628', '600629', '600630', '600631', '600633', '600635', '600636', '600637',
        '600638', '600639', '600640', '600641', '600642', '600643', '600644', '600645', '600646', '600647',
        '600648', '600649', '600650', '600651', '600652', '600653', '600655', '600656', '600657', '600658',
        '600660', '600661', '600662', '600663', '600664', '600665', '600666', '600667', '600668', '600670',
        '600671', '600673', '600674', '600675', '600676', '600677', '600678', '600679', '600680', '600681',
        '600682', '600683', '600684', '600685', '600686', '600687', '600688', '600689', '600690', '600691',
        '600692', '600693', '600694', '600695', '600696', '600697', '600698', '600699', '600701', '600702',
        '600703', '600704', '600705', '600706', '600707', '600708', '600710', '600711', '600712', '600715',
        '600716', '600717', '600718', '600719', '600720', '600721', '600722', '600723', '600724', '600725',
        '600726', '600727', '600728', '600729', '600730', '600731', '600732', '600733', '600734', '600735',
        '600736', '600737', '600738', '600739', '600740', '600741', '600742', '600743', '600744', '600745',
        '600746', '600747', '600748', '600749', '600750', '600751', '600752', '600753', '600754', '600755',
        '600756', '600757', '600758', '600759', '600760', '600761', '600762', '600763', '600764', '600765',
        '600766', '600767', '600768', '600770', '600771', '600773', '600774', '600775', '600777', '600778',
        '600779', '600780', '600781', '600782', '600783', '600784', '600785', '600786', '600787', '600788',
        '600789', '600790', '600791', '600792', '600793', '600794', '600795', '600796', '600797', '600798',
        '600799', '600800', '600801', '600802', '600803', '600804', '600805', '600806', '600807', '600808',
        '600809', '600810', '600811', '600812', '600814', '600815', '600816', '600817', '600818', '600819',
        '600820', '600821', '600822', '600823', '600824', '600825', '600826', '600827', '600828', '600829',
        '600830', '600831', '600832', '600833', '600834', '600835', '600836', '600837', '600838', '600839',
        '600840', '600841', '600842', '600843', '600844', '600845', '600846', '600847', '600848', '600849',
        '600850', '600851', '600852', '600853', '600854', '600855', '600856', '600857', '600858', '600859',
        '600860', '600861', '600862', '600863', '600864', '600865', '600866', '600867', '600868', '600869',
        '600870', '600871', '600872', '600873', '600874', '600875', '600876', '600877', '600879', '600880',
        '600881', '600882', '600883', '600884', '600885', '600886', '600887', '600888', '600889', '600890',
        '600891', '600892', '600893', '600894', '600895', '600896', '600897', '600898', '600899', '600900',
        '600901', '600902', '600903', '600905', '600906', '600907', '600908', '600909', '600910', '600911',
        '600912', '600913', '600916', '600917', '600918', '600919', '600920', '600921', '600922', '600923',
        '600925', '600926', '600927', '600928', '600929', '600930', '600931', '600932', '600933', '600935',
        '600936', '600937', '600938', '600939', '600940', '600941', '600942', '600943', '600945', '600946',
        '600947', '600948', '600949', '600950', '600951', '600952', '600953', '600955', '600956', '600957',
        '600958', '600959', '600960', '600961', '600962', '600963', '600965', '600966', '600967', '600968',
        '600969', '600970', '600971', '600972', '600973', '600974', '600975', '600976', '600977', '600978',
        '600979', '600980', '600981', '600982', '600983', '600984', '600985', '600986', '600987', '600988',
        '600989', '600990', '600991', '600992', '600993', '600995', '600996', '600997', '600998', '600999',

        // 创业板热门
        '300001', '300002', '300003', '300004', '300005', '300006', '300007', '300008', '300009', '300010',
        '300011', '300012', '300013', '300014', '300015', '300016', '300017', '300018', '300019', '300020',
        '300021', '300022', '300023', '300024', '300025', '300026', '300027', '300028', '300029', '300030',
        '300031', '300032', '300033', '300034', '300035', '300036', '300037', '300038', '300039', '300040',
        '300041', '300042', '300043', '300044', '300045', '300046', '300047', '300048', '300049', '300050',
        '300051', '300052', '300053', '300054', '300055', '300056', '300057', '300058', '300059', '300060',
        '300061', '300062', '300063', '300064', '300065', '300066', '300067', '300068', '300069', '300070',
        '300071', '300072', '300073', '300074', '300075', '300076', '300077', '300078', '300079', '300080',
        '300081', '300082', '300083', '300084', '300085', '300086', '300087', '300088', '300089', '300090',
        '300091', '300092', '300093', '300094', '300095', '300096', '300097', '300098', '300099', '300100',
        '300101', '300102', '300103', '300104', '300105', '300106', '300107', '300108', '300109', '300110',
        '300111', '300112', '300113', '300114', '300115', '300116', '300117', '300118', '300119', '300120',
        '300121', '300122', '300123', '300124', '300125', '300126', '300127', '300128', '300129', '300130',
        '300131', '300132', '300133', '300134', '300135', '300136', '300137', '300138', '300139', '300140',
        '300141', '300142', '300143', '300144', '300145', '300146', '300147', '300148', '300149', '300150',
        '300151', '300152', '300153', '300154', '300155', '300156', '300157', '300158', '300159', '300160',
        '300161', '300162', '300163', '300164', '300165', '300166', '300167', '300168', '300169', '300170',
        '300171', '300172', '300173', '300174', '300175', '300176', '300177', '300178', '300179', '300180',
        '300181', '300182', '300183', '300184', '300185', '300186', '300187', '300188', '300189', '300190',
        '300191', '300192', '300193', '300194', '300195', '300196', '300197', '300198', '300199', '300200',
        '300201', '300202', '300203', '300204', '300205', '300206', '300207', '300208', '300209', '300210',
        '300211', '300212', '300213', '300214', '300215', '300216', '300217', '300218', '300219', '300220',
        '300221', '300222', '300223', '300224', '300225', '300226', '300227', '300228', '300229', '300230',
        '300231', '300232', '300233', '300234', '300235', '300236', '300237', '300238', '300239', '300240',
        '300241', '300242', '300243', '300244', '300245', '300246', '300247', '300248', '300249', '300250',
        '300251', '300252', '300253', '300254', '300255', '300256', '300257', '300258', '300259', '300260',
        '300261', '300262', '300263', '300264', '300265', '300266', '300267', '300268', '300269', '300270',
        '300271', '300272', '300273', '300274', '300275', '300276', '300277', '300278', '300279', '300280',
        '300281', '300282', '300283', '300284', '300285', '300286', '300287', '300288', '300289', '300290',
        '300291', '300292', '300293', '300294', '300295', '300296', '300297', '300298', '300299', '300300',
        '300301', '300302', '300303', '300304', '300305', '300306', '300307', '300308', '300309', '300310',
        '300311', '300312', '300313', '300314', '300315', '300316', '300317', '300318', '300319', '300320',
        '300321', '300322', '300323', '300324', '300325', '300326', '300327', '300328', '300329', '300330',
        '300331', '300332', '300333', '300334', '300335', '300336', '300337', '300338', '300339', '300340',
        '300341', '300342', '300343', '300344', '300345', '300346', '300347', '300348', '300349', '300350',
        '300351', '300352', '300353', '300354', '300355', '300356', '300357', '300358', '300359', '300360',
        '300361', '300362', '300363', '300364', '300365', '300366', '300367', '300368', '300369', '300370',
        '300371', '300372', '300373', '300374', '300375', '300376', '300377', '300378', '300379', '300380',
        '300381', '300382', '300383', '300384', '300385', '300386', '300387', '300388', '300389', '300390',
        '300391', '300392', '300393', '300394', '300395', '300396', '300397', '300398', '300399', '300400',
        '300401', '300402', '300403', '300404', '300405', '300406', '300407', '300408', '300409', '300410',
        '300411', '300412', '300413', '300414', '300415', '300416', '300417', '300418', '300419', '300420',
        '300421', '300422', '300423', '300424', '300425', '300426', '300427', '300428', '300429', '300430',
        '300431', '300432', '300433', '300434', '300435', '300436', '300437', '300438', '300439', '300440',
        '300441', '300442', '300443', '300444', '300445', '300446', '300447', '300448', '300449', '300450',
        '300451', '300452', '300453', '300454', '300455', '300456', '300457', '300458', '300459', '300460',
        '300461', '300462', '300463', '300464', '300465', '300466', '300467', '300468', '300469', '300470',
        '300471', '300472', '300473', '300474', '300475', '300476', '300477', '300478', '300479', '300480',
        '300481', '300482', '300483', '300484', '300485', '300486', '300487', '300488', '300489', '300490',
        '300491', '300492', '300493', '300494', '300495', '300496', '300497', '300498', '300499', '300500',
        '300501', '300502', '300503', '300504', '300505', '300506', '300507', '300508', '300509', '300510',
        '300511', '300512', '300513', '300514', '300515', '300516', '300517', '300518', '300519', '300520',
        '300521', '300522', '300523', '300524', '300525', '300526', '300527', '300528', '300529', '300530',
        '300531', '300532', '300533', '300534', '300535', '300536', '300537', '300538', '300539', '300540',
        '300541', '300542', '300543', '300544', '300545', '300546', '300547', '300548', '300549', '300550',
        '300551', '300552', '300553', '300554', '300555', '300556', '300557', '300558', '300559', '300560',
        '300561', '300562', '300563', '300564', '300565', '300566', '300567', '300568', '300569', '300570',
        '300571', '300572', '300573', '300574', '300575', '300576', '300577', '300578', '300579', '300580',
        '300581', '300582', '300583', '300584', '300585', '300586', '300587', '300588', '300589', '300590',
        '300591', '300592', '300593', '300594', '300595', '300596', '300597', '300598', '300599', '300600',
        '300601', '300602', '300603', '300604', '300605', '300606', '300607', '300608', '300609', '300610',
        '300611', '300612', '300613', '300614', '300615', '300616', '300617', '300618', '300619', '300620',
        '300621', '300622', '300623', '300624', '300625', '300626', '300627', '300628', '300629', '300630',
        '300631', '300632', '300633', '300634', '300635', '300636', '300637', '300638', '300639', '300640',
        '300641', '300642', '300643', '300644', '300645', '300646', '300647', '300648', '300649', '300650',
        '300651', '300652', '300653', '300654', '300655', '300656', '300657', '300658', '300659', '300660',
        '300661', '300662', '300663', '300664', '300665', '300666', '300667', '300668', '300669', '300670',
        '300671', '300672', '300673', '300674', '300675', '300676', '300677', '300678', '300679', '300680',
        '300681', '300682', '300683', '300684', '300685', '300686', '300687', '300688', '300689', '300690',
        '300691', '300692', '300693', '300694', '300695', '300696', '300697', '300698', '300699', '300700',
        '300701', '300702', '300703', '300704', '300705', '300706', '300707', '300708', '300709', '300710',
        '300711', '300712', '300713', '300714', '300715', '300716', '300717', '300718', '300719', '300720',
        '300721', '300722', '300723', '300724', '300725', '300726', '300727', '300728', '300729', '300730',
        '300731', '300732', '300733', '300734', '300735', '300736', '300737', '300738', '300739', '300740',
        '300741', '300742', '300743', '300744', '300745', '300746', '300747', '300748', '300749', '300750',
        '300751', '300752', '300753', '300754', '300755', '300756', '300757', '300758', '300759', '300760',
        '300761', '300762', '300763', '300764', '300765', '300766', '300767', '300768', '300769', '300770',
        '300771', '300772', '300773', '300774', '300775', '300776', '300777', '300778', '300779', '300780',
        '300781', '300782', '300783', '300784', '300785', '300786', '300787', '300788', '300789', '300790',
        '300791', '300792', '300793', '300794', '300795', '300796', '300797', '300798', '300799', '300800',
        '300801', '300802', '300803', '300804', '300805', '300806', '300807', '300808', '300809', '300810',
        '300811', '300812', '300813', '300814', '300815', '300816', '300817', '300818', '300819', '300820',
        '300821', '300822', '300823', '300824', '300825', '300826', '300827', '300828', '300829', '300830',
        '300831', '300832', '300833', '300834', '300835', '300836', '300837', '300838', '300839', '300840',
        '300841', '300842', '300843', '300844', '300845', '300846', '300847', '300848', '300849', '300850',
        '300851', '300852', '300853', '300854', '300855', '300856', '300857', '300858', '300859', '300860',
        '300861', '300862', '300863', '300864', '300865', '300866', '300867', '300868', '300869', '300870',
        '300871', '300872', '300873', '300874', '300875', '300876', '300877', '300878', '300879', '300880',
        '300881', '300882', '300883', '300884', '300885', '300886', '300887', '300888', '300889', '300890',
        '300891', '300892', '300893', '300894', '300895', '300896', '300897', '300898', '300899', '300900',
        '300901', '300902', '300903', '300904', '300905', '300906', '300907', '300908', '300909', '300910',
        '300911', '300912', '300913', '300914', '300915', '300916', '300917', '300918', '300919', '300920',
        '300921', '300922', '300923', '300924', '300925', '300926', '300927', '300928', '300929', '300930',
        '300931', '300932', '300933', '300934', '300935', '300936', '300937', '300938', '300939', '300940',
        '300941', '300942', '300943', '300944', '300945', '300946', '300947', '300948', '300949', '300950',
        '300951', '300952', '300953', '300954', '300955', '300956', '300957', '300958', '300959', '300960',
        '300961', '300962', '300963', '300964', '300965', '300966', '300967', '300968', '300969', '300970',
        '300971', '300972', '300973', '300974', '300975', '300976', '300977', '300978', '300979', '300980',
        '300981', '300982', '300983', '300984', '300985', '300986', '300987', '300988', '300989', '300990',
        '300991', '300992', '300993', '300994', '300995', '300996', '300997', '300998', '300999',

        // 科创板热门
        '688001', '688002', '688003', '688005', '688006', '688007', '688008', '688009', '688010', '688011',
        '688012', '688015', '688016', '688017', '688018', '688019', '688020', '688021', '688022', '688023',
        '688025', '688026', '688027', '688028', '688029', '688030', '688031', '688032', '688033', '688035',
        '688036', '688037', '688038', '688039', '688040', '688041', '688042', '688043', '688044', '688045',
        '688046', '688047', '688048', '688049', '688050', '688051', '688052', '688053', '688055', '688056',
        '688057', '688058', '688059', '688060', '688061', '688062', '688063', '688064', '688065', '688066',
        '688067', '688068', '688069', '688070', '688071', '688072', '688073', '688075', '688076', '688077',
        '688078', '688079', '688080', '688081', '688082', '688083', '688084', '688085', '688086', '688087',
        '688088', '688089', '688090', '688091', '688092', '688093', '688094', '688095', '688096', '688097',
        '688098', '688099', '688100', '688101', '688102', '688103', '688105', '688106', '688107', '688108',
        '688109', '688110', '688111', '688112', '688113', '688115', '688116', '688117', '688118', '688119',
        '688120', '688121', '688122', '688123', '688125', '688126', '688127', '688128', '688129', '688130',
        '688131', '688132', '688133', '688136', '688137', '688138', '688139', '688140', '688141', '688143',
        '688144', '688145', '688146', '688147', '688148', '688149', '688150', '688151', '688152', '688153',
        '688155', '688156', '688157', '688158', '688159', '688160', '688161', '688162', '688163', '688165',
        '688166', '688167', '688168', '688169', '688170', '688171', '688172', '688173', '688175', '688176',
        '688177', '688178', '688179', '688180', '688181', '688182', '688183', '688185', '688186', '688187',
        '688188', '688189', '688190', '688191', '688192', '688193', '688195', '688196', '688197', '688198',
        '688199', '688200', '688201', '688202', '688203', '688205', '688206', '688207', '688208', '688209',
        '688210', '688211', '688212', '688215', '688216', '688217', '688218', '688219', '688220', '688221',
        '688222', '688223', '688225', '688226', '688227', '688228', '688229', '688230', '688231', '688232',
        '688233', '688235', '688236', '688237', '688238', '688239', '688240', '688241', '688242', '688243',
        '688245', '688246', '688247', '688248', '688249', '688250', '688251', '688252', '688253', '688255',
        '688256', '688257', '688258', '688259', '688260', '688261', '688262', '688263', '688265', '688266',
        '688267', '688268', '688269', '688270', '688271', '688272', '688273', '688274', '688275', '688276',
        '688277', '688278', '688279', '688280', '688281', '688282', '688283', '688285', '688286', '688287',
        '688288', '688289', '688290', '688291', '688292', '688293', '688295', '688296', '688297', '688298',
        '688299', '688300', '688301', '688302', '688303', '688305', '688306', '688307', '688308', '688309',
        '688311', '688312', '688313', '688315', '688316', '688317', '688318', '688319', '688320', '688321',
        '688322', '688323', '688325', '688326', '688327', '688328', '688329', '688330', '688331', '688332',
        '688333', '688335', '688336', '688337', '688338', '688339', '688340', '688341', '688342', '688343',
        '688345', '688346', '688347', '688348', '688349', '688350', '688351', '688352', '688353', '688355',
        '688356', '688357', '688358', '688359', '688360', '688361', '688362', '688363', '688365', '688366',
        '688367', '688368', '688369', '688370', '688371', '688372', '688373', '688375', '688376', '688377',
        '688378', '688379', '688380', '688381', '688382', '688383', '688385', '688386', '688387', '688388',
        '688389', '688390', '688391', '688392', '688393', '688395', '688396', '688397', '688398', '688399',
        '688400', '688401', '688402', '688403', '688405', '688406', '688407', '688408', '688409', '688410',
        '688411', '688412', '688413', '688415', '688416', '688417', '688418', '688419', '688420', '688421',
        '688422', '688423', '688425', '688426', '688427', '688428', '688429', '688430', '688431', '688432',
        '688433', '688435', '688436', '688437', '688438', '688439', '688440', '688441', '688442', '688443',
        '688445', '688446', '688447', '688448', '688449', '688450', '688451', '688452', '688453', '688455',
        '688456', '688457', '688458', '688459', '688460', '688461', '688462', '688463', '688465', '688466',
        '688467', '688468', '688469', '688470', '688471', '688472', '688473', '688475', '688476', '688477',
        '688478', '688479', '688480', '688481', '688482', '688483', '688485', '688486', '688487', '688488',
        '688489', '688490', '688491', '688492', '688493', '688495', '688496', '688497', '688498', '688499',
        '688500', '688501', '688502', '688503', '688505', '688506', '688507', '688508', '688509', '688510',
        '688511', '688512', '688513', '688515', '688516', '688517', '688518', '688519', '688520', '688521',
        '688522', '688523', '688525', '688526', '688527', '688528', '688529', '688530', '688531', '688532',
        '688533', '688535', '688536', '688537', '688538', '688539', '688540', '688541', '688542', '688543',
        '688545', '688546', '688547', '688548', '688549', '688550', '688551', '688552', '688553', '688555',
        '688556', '688557', '688558', '688559', '688560', '688561', '688562', '688563', '688565', '688566',
        '688567', '688568', '688569', '688570', '688571', '688572', '688573', '688575', '688576', '688577',
        '688578', '688579', '688580', '688581', '688582', '688583', '688585', '688586', '688587', '688588',
        '688589', '688590', '688591', '688592', '688593', '688595', '688596', '688597', '688598', '688599',
        '688600', '688601', '688602', '688603', '688605', '688606', '688607', '688608', '688609', '688610',
        '688611', '688612', '688613', '688615', '688616', '688617', '688618', '688619', '688620', '688621',
        '688622', '688623', '688625', '688626', '688627', '688628', '688629', '688630', '688631', '688632',
        '688633', '688635', '688636', '688637', '688638', '688639', '688640', '688641', '688642', '688643',
        '688645', '688646', '688647', '688648', '688649', '688650', '688651', '688652', '688653', '688655',
        '688656', '688657', '688658', '688659', '688660', '688661', '688662', '688663', '688665', '688666',
        '688667', '688668', '688669', '688670', '688671', '688672', '688673', '688675', '688676', '688677',
        '688678', '688679', '688680', '688681', '688682', '688683', '688685', '688686', '688687', '688688',
        '688689', '688690', '688691', '688692', '688693', '688695', '688696', '688697', '688698', '688699',
        '688700', '688701', '688702', '688703', '688705', '688706', '688707', '688708', '688709', '688710',
        '688711', '688712', '688713', '688715', '688716', '688717', '688718', '688719', '688720', '688721',
        '688722', '688723', '688725', '688726', '688727', '688728', '688729', '688730', '688731', '688732',
        '688733', '688735', '688736', '688737', '688738', '688739', '688740', '688741', '688742', '688743',
        '688745', '688746', '688747', '688748', '688749', '688750', '688751', '688752', '688753', '688755',
        '688756', '688757', '688758', '688759', '688760', '688761', '688762', '688763', '688765', '688766',
        '688767', '688768', '688769', '688770', '688771', '688772', '688773', '688775', '688776', '688777',
        '688778', '688779', '688780', '688781', '688782', '688783', '688785', '688786', '688787', '688788',
        '688789', '688790', '688791', '688792', '688793', '688795', '688796', '688797', '688798', '688799',
        '688800', '688801', '688802', '688803', '688805', '688806', '688807', '688808', '688809', '688810',
        '688811', '688812', '688813', '688815', '688816', '688817', '688818', '688819', '688820', '688821',
        '688822', '688823', '688825', '688826', '688827', '688828', '688829', '688830', '688831', '688832',
        '688833', '688835', '688836', '688837', '688838', '688839', '688840', '688841', '688842', '688843',
        '688845', '688846', '688847', '688848', '688849', '688850', '688851', '688852', '688853', '688855',
        '688856', '688857', '688858', '688859', '688860', '688861', '688862', '688863', '688865', '688866',
        '688867', '688868', '688869', '688870', '688871', '688872', '688873', '688875', '688876', '688877',
        '688878', '688879', '688880', '688881', '688882', '688883', '688885', '688886', '688887', '688888',
        '688889', '688890', '688891', '688892', '688893', '688895', '688896', '688897', '688898', '688899',
        '688900', '688901', '688902', '688903', '688905', '688906', '688907', '688908', '688909', '688910',
        '688911', '688912', '688913', '688915', '688916', '688917', '688918', '688919', '688920', '688921',
        '688922', '688923', '688925', '688926', '688927', '688928', '688929', '688930', '688931', '688932',
        '688933', '688935', '688936', '688937', '688938', '688939', '688940', '688941', '688942', '688943',
        '688945', '688946', '688947', '688948', '688949', '688950', '688951', '688952', '688953', '688955',
        '688956', '688957', '688958', '688959', '688960', '688961', '688962', '688963', '688965', '688966',
        '688967', '688968', '688969', '688970', '688971', '688972', '688973', '688975', '688976', '688977',
        '688978', '688979', '688980', '688981', '688982', '688983', '688985', '688986', '688987', '688988',
        '688989', '688990', '688991', '688992', '688993', '688995', '688996', '688997', '688998', '688999'
    ];

    // 批量查询股票，避免过多API调用
    const batchSize = 20;
    for (let i = 0; i < searchPriorityCodes.length && results.length < maxResults; i += batchSize) {
        const batch = searchPriorityCodes.slice(i, i + batchSize);
        const promises = batch.map(code => fetchTencentStockData(code));

        try {
            const batchResults = await Promise.all(promises);

            for (let j = 0; j < batchResults.length && results.length < maxResults; j++) {
                const stockData = batchResults[j];
                if (stockData && stockData.name) {
                    const stockNameLower = stockData.name.toLowerCase();
                    // 模糊匹配：检查搜索词是否在股票名称中
                    if (stockNameLower.includes(searchTerms) || searchTerms.includes(stockNameLower)) {
                        console.log(`找到匹配股票: ${stockData.name} (${stockData.code})`);
                        results.push(stockData);

                        // 缓存搜索结果
                        stockNameCache.set(stockData.name, stockData.code);
                    }
                }
            }
        } catch (error) {
            console.error('批量查询股票数据失败:', error);
        }

        // 避免API调用过于频繁
        if (i + batchSize < searchPriorityCodes.length) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }
    }

    console.log(`搜索完成，找到 ${results.length} 个匹配结果`);
    return results;
}

// 智能验证和纠正标的代码
async function smartValidateAndCorrect(stockCode) {
    console.log('开始智能验证:', stockCode);

    let originalInput = stockCode.trim();
    let correctedCode = originalInput;

    // 1. 处理格式问题：移除.SH/.SZ后缀
    if (/^\d{6}\.(SH|SZ)$/i.test(correctedCode)) {
        correctedCode = correctedCode.replace(/\.(SH|SZ)$/i, '');
        console.log('格式纠正：移除交易所后缀', originalInput, '->', correctedCode);

        // 立即测试纠正后的代码
        const testResult = await fetchTencentStockData(correctedCode);
        if (testResult) {
            console.log('格式纠正成功，找到数据');
            return testResult;
        }
    }

    // 2. 处理6位数字代码：尝试不同交易所
    if (/^\d{6}$/.test(correctedCode)) {
        const prefixes = ['sz', 'sh'];

        for (const prefix of prefixes) {
            const testCode = prefix + correctedCode;
            console.log('测试交易所前缀:', testCode);

            const testResult = await fetchTencentStockDataDirect(testCode);
            if (testResult) {
                console.log('交易所前缀测试成功:', prefix);
                // 返回标准化的6位代码
                return {
                    ...testResult,
                    code: correctedCode
                };
            }
        }
    }

    // 3. 处理可能的公司名称：通过智能搜索
    if (!/^\d+$/.test(correctedCode) && correctedCode.length > 1) {
        console.log('尝试公司名称搜索:', correctedCode);

        const searchResults = await searchStockByName(correctedCode, 5);
        if (searchResults.length > 0) {
            const bestMatch = searchResults[0]; // 取第一个最佳匹配
            console.log('智能搜索找到匹配:', correctedCode, '->', bestMatch.code, bestMatch.name);

            // 自动添加到映射表
            stockNameCache.set(correctedCode, bestMatch.code);
            console.log('自动添加到缓存:', correctedCode, '=', bestMatch.code);

            return bestMatch;
        }
    }

    console.log('智能验证未找到有效数据');
    return null;
}

// 直接调用腾讯API（用于内部测试）
async function fetchTencentStockDataDirect(code) {
    try {
        const tencentUrl = `https://qt.gtimg.cn/q=${code}`;

        const response = await axios.get(tencentUrl, {
            timeout: 3000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.qq.com/'
            },
            responseType: 'arraybuffer'
        });

        const data = iconv.decode(Buffer.from(response.data), 'gbk');

        if (data.includes('v_pv_none_match="1"')) {
            return null;
        }

        const match = data.match(/v_(.+?)="(.+?)";/);

        if (match && match[2] && match[2].length > 10) {
            const parts = match[2].split('~');
            if (parts.length > 30 && parts[1] && parts[3]) {
                const currentPrice = parseFloat(parts[3]);
                const yesterdayClose = parseFloat(parts[4]);
                const change = currentPrice - yesterdayClose;
                const changePercent = yesterdayClose > 0 ? (change / yesterdayClose) * 100 : 0;

                return {
                    code: code.replace(/^(sh|sz)/, ''),
                    name: parts[1].trim(),
                    price: currentPrice || 0,
                    change: change || 0,
                    changePercent: changePercent || 0,
                    open: parseFloat(parts[5]) || 0,
                    high: parseFloat(parts[33]) || 0,
                    low: parseFloat(parts[34]) || 0,
                    volume: parseInt(parts[6]) || 0,
                    updateTime: new Date().toISOString()
                };
            }
        }

        return null;
    } catch (error) {
        return null;
    }
}

// 股票搜索API端点
app.get('/api/search/:keyword', async (req, res) => {
    try {
        console.log('收到股票搜索请求:', req.params.keyword);
        const keyword = req.params.keyword.trim();

        if (!keyword || keyword.length < 2) {
            return res.status(400).json({
                success: false,
                error: '搜索关键词至少需要2个字符'
            });
        }

        // 搜索股票
        const searchResults = await searchStockByName(keyword, 10);

        if (searchResults.length > 0) {
            res.json({
                success: true,
                data: searchResults,
                count: searchResults.length,
                message: `找到 ${searchResults.length} 个匹配结果`
            });
        } else {
            res.json({
                success: true,
                data: [],
                count: 0,
                message: '未找到匹配的股票'
            });
        }

    } catch (error) {
        console.error('股票搜索失败:', error);
        res.status(500).json({
            success: false,
            error: '搜索失败，请重试'
        });
    }
});

// 标的数据API端点
app.get('/api/stock/:code', async (req, res) => {
    try {
        console.log('收到股票请求:', req.params.code);
        let stockCode = req.params.code.trim();

        // 检查是否为交易时间
        const trading = isTradingHours();
        const isNonTradingHours = !trading;

        // 如果是名称，转换为代码
        if (stockNameMap[stockCode]) {
            stockCode = stockNameMap[stockCode];
            console.log('名称映射转换:', stockCode);
        }

        // 清理错误的巨人网络映射
        if (stockCode === '002555' && req.params.code.includes('巨人')) {
            console.log('检测到错误的巨人网络映射，使用正确代码002558');
            stockCode = '002558';
        }

        // 首先尝试腾讯财经API（更稳定）
        const tencentResult = await fetchTencentStockData(stockCode);
        if (tencentResult) {
            res.json({
                success: true,
                data: tencentResult,
                isTradingHours: trading,
                isNonTradingHours: isNonTradingHours,
                message: isNonTradingHours ? '当前为非交易时间，数据不会实时更新' : undefined
            });
            return;
        }

        // 如果腾讯API失败，尝试新浪财经API
        const sinaResult = await fetchSinaStockData(stockCode);
        if (sinaResult) {
            res.json({
                success: true,
                data: sinaResult,
                isTradingHours: trading,
                isNonTradingHours: isNonTradingHours,
                message: isNonTradingHours ? '当前为非交易时间，数据不会实时更新' : undefined
            });
            return;
        }

        // 如果都失败了，启动智能验证
        console.log('常规API失败，启动智能验证...');
        const smartResult = await smartValidateAndCorrect(req.params.code);
        if (smartResult) {
            res.json({
                success: true,
                data: smartResult,
                isTradingHours: trading,
                isNonTradingHours: isNonTradingHours,
                message: isNonTradingHours ? '当前为非交易时间，通过智能验证找到匹配数据' : '通过智能验证找到匹配数据'
            });
            return;
        }

        // 如果智能验证也失败，返回404
        console.log('智能验证失败，返回404');
        res.status(404).json({
            success: false,
            error: '未找到该标的数据，请检查代码或名称'
        });

    } catch (error) {
        console.error('获取标的数据失败:', error);
        res.status(500).json({
            success: false,
            error: '获取标的数据失败'
        });
    }
});

// 腾讯财经API
async function fetchTencentStockData(stockCode) {
    try {
        console.log('尝试腾讯API获取股票数据:', stockCode);

        // 处理股票代码格式
        let code = stockCode.toUpperCase();
        let originalCode = stockCode;

        // 如果已经是sh/sz开头，直接使用（但要确保是小写）
        if (/^(SH|SZ)\d{6}$/.test(code)) {
            code = code.toLowerCase();
        }
        // 如果是6位数字，添加交易所前缀
        else if (/^\d{6}$/.test(code)) {
            if (code.startsWith('6')) {
                code = 'sh' + code; // 上海交易所
            } else if (code.startsWith('0') || code.startsWith('3')) {
                code = 'sz' + code; // 深圳交易所
            }
        }
        // 如果已经是小写sh/sz开头，保持不变
        else if (/^(sh|sz)\d{6}$/.test(code)) {
            // 已经是正确格式，无需修改
        }

        const tencentUrl = `https://qt.gtimg.cn/q=${code}`;
        console.log('腾讯API请求URL:', tencentUrl);

        const response = await axios.get(tencentUrl, {
            timeout: 5000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.qq.com/'
            },
            responseType: 'arraybuffer'
        });

        // 处理GBK编码
        const data = iconv.decode(Buffer.from(response.data), 'gbk');
        console.log('腾讯API返回数据长度:', data.length);

        // 检查是否返回了"无匹配"的数据
        if (data.includes('v_pv_none_match="1"')) {
            console.log('腾讯API未找到匹配数据');
            return null;
        }

        const match = data.match(/v_(.+?)="(.+?)";/);

        if (match && match[2] && match[2].length > 10) {
            const parts = match[2].split('~');
            if (parts.length > 30 && parts[1] && parts[3]) {
                const currentPrice = parseFloat(parts[3]);
                const yesterdayClose = parseFloat(parts[4]);
                const change = currentPrice - yesterdayClose;
                const changePercent = yesterdayClose > 0 ? (change / yesterdayClose) * 100 : 0;

                console.log('腾讯API解析成功:', parts[1], currentPrice);

                return {
                    code: originalCode.replace(/^(SH|SZ)(\d{6})$/, '$2'), // 移除交易所前缀，只保留6位代码
                    name: parts[1].trim(),
                    price: currentPrice || 0,
                    change: change || 0,
                    changePercent: changePercent || 0,
                    open: parseFloat(parts[5]) || 0,
                    high: parseFloat(parts[33]) || 0,
                    low: parseFloat(parts[34]) || 0,
                    volume: parseInt(parts[6]) || 0,
                    updateTime: new Date().toISOString()
                };
            }
        }

        console.log('腾讯API未返回有效数据');
        return null;
    } catch (error) {
        console.error('腾讯API获取标的数据失败:', error.message);
        return null;
    }
}

// 新浪财经API（备用）
async function fetchSinaStockData(stockCode) {
    try {
        // 处理股票代码格式
        let code = stockCode.toUpperCase();

        // 如果是6位数字，添加交易所后缀
        if (/^\d{6}$/.test(code)) {
            if (code.startsWith('6')) {
                code = code + '.SH'; // 上海交易所
            } else if (code.startsWith('0') || code.startsWith('3')) {
                code = code + '.SZ'; // 深圳交易所
            }
        }

        // 使用新浪财经API获取数据
        const sinaUrl = `https://hq.sinajs.cn/list=${code}`;

        const response = await axios.get(sinaUrl, {
            timeout: 5000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        });

        const data = response.data;

        // 解析新浪API返回的数据
        const match = data.match(/var hq_str_(.+?)="(.+?)";/);
        if (match && match[2]) {
            const parts = match[2].split(',');
            if (parts.length > 30 && parts[0] && parts[3]) {
                const currentPrice = parseFloat(parts[3]);
                const yesterdayClose = parseFloat(parts[2]);
                const change = currentPrice - yesterdayClose;
                const changePercent = (change / yesterdayClose) * 100;

                return {
                    code: match[1],
                    name: parts[0],
                    price: currentPrice || 0,
                    change: change || 0,
                    changePercent: changePercent || 0,
                    open: parseFloat(parts[1]) || 0,
                    high: parseFloat(parts[4]) || 0,
                    low: parseFloat(parts[5]) || 0,
                    volume: parseInt(parts[8]) || 0,
                    updateTime: new Date().toISOString()
                };
            }
        }

        return null;
    } catch (error) {
        console.error('新浪API获取标的数据失败:', error);
        return null;
    }
}


// 健康检查端点
app.get('/health', (req, res) => {
    res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// 启动服务器
// K线图API端点
app.get('/api/kline/:code', async (req, res) => {
    try {
        console.log('收到K线图请求:', req.params.code);
        const stockCode = req.params.code.trim();
        const period = req.query.period || 'd'; // 默认日K线
        const count = parseInt(req.query.count) || 30; // 默认30天

        // 模拟K线数据（日K线）
        const klineData = [];
        const today = new Date();
        let basePrice = 10 + Math.random() * 90; // 基准价格在10-100之间

        for (let i = 0; i < count; i++) {
            const date = new Date(today);
            date.setDate(date.getDate() - (count - i - 1)); // 从count-1天前开始

            const price = basePrice + (Math.random() - 0.5) * 5;
            const change = (Math.random() - 0.5) * 2; // ±1%
            const changePercent = (change / price) * 100;

            const open = price - (Math.random() - 0.5) * 1;
            const high = price + Math.random() * 2;
            const low = price - Math.random() * 2;

            klineData.push({
                date: date.toISOString().split('T')[0],
                open: open.toFixed(2),
                close: price.toFixed(2),
                high: high.toFixed(2),
                low: low.toFixed(2),
                volume: Math.floor(1000 + Math.random() * 9000), // 成交量
                change: change.toFixed(2),
                changePercent: changePercent.toFixed(2)
            });

            // 为下一个价格设置基准，确保价格连续性
            basePrice = parseFloat(price);
        }

        res.json({
            success: true,
            data: klineData,
            period: period,
            count: count,
            stockCode: stockCode
        });

    } catch (error) {
        console.error('获取K线数据失败:', error);
        res.status(500).json({
            success: false,
            error: '获取K线数据失败'
        });
    }
});

app.listen(PORT, () => {
    console.log(`数据监控服务器运行在 http://localhost:${PORT}`);
    console.log(`请在浏览器中访问: http://localhost:${PORT}`);
    console.log('健康检查: http://localhost:3000/health');
});